﻿
package extremefx.modules.seaDragon {
	import extremefx.geom.Size;	
	import extremefx.modules.seaDragon.TileSource;
	
	/**
	 * @author Marcelo Volmaro
	 */
	public final class DziTileSource extends TileSource {

		private var _fileFormat:String;
		private var _levelRects:Array;
		private var _tilesUrl:String;
//		private var _displayRects:Vector.<DisplayRect>;

		public function DziTileSource(pSize:Size, pTileSize:uint, pTileOverlay:uint, pTilesUrl:String, pFileFormat:String, pDisplayRecs:Vector.<DisplayRect>) {
			super(pSize, pTileSize, pTileOverlay);
			
			_fileFormat = pFileFormat;
			_levelRects = [];
//			_displayRects = pDisplayRecs;
			_tilesUrl = pTilesUrl;
			
			for each(var dr:DisplayRect in pDisplayRecs){
				for(var level:uint = dr.minLevel; level < dr.maxLevel; ++level){
					if (!_levelRects[level]) _levelRects[level] = [];
					_levelRects[level].push(dr);
				}
			}
		}
		
		override public function getTileUrl(pLevel:uint, pX:uint, pY:uint):String {
			return _tilesUrl + pLevel + "/" + pX + "_" + pY + "." + _fileFormat;
		}
		
		override public function tileExists(pLevel:uint, pX:uint, pY:uint):Boolean {
			var rects:Array = _levelRects[pLevel];
			if (!rects || !rects.length) {
				return true;
			}
			
			var scale:Number = getLevelScale(pLevel);
			
			for each(var rect:DisplayRect in rects){
				if (pLevel < rect.minLevel || pLevel > rect.maxLevel) {
					continue;
				}
				
				var xMin:Number = rect.x * scale;
				var yMin:Number = rect.y * scale;
				var xMax:Number = xMin + rect.width * scale;
				var yMax:Number = yMin + rect.height * scale;
				xMin = Math.floor(xMin / tileSize);
				yMin = Math.floor(yMin / tileSize);
				xMax = Math.ceil(xMax / tileSize);
				yMax = Math.ceil(yMax / tileSize);
				
				if (xMin <= pX && pX < xMax && yMin <= pY && pY < yMax) {
					return true;
				}
			}
			
			return false;
		}
	}
}
